#include "types.h"
#include <stdint.h>
#include <stdio.h>

void deduceKey (uchar* K1, uchar* K2, uchar* K)
{
  uint8_t i; 
  uint8_t j;

  /* Mapping table from the 56-bits key K to the first round-key K1 */
  static uint8_t mapKtoK1[48]=
    {
      14, 17, 11, 24, 1, 5, 3, 0,
      15, 6, 29, 10, 23, 19, 12, 4,
      26, 8, 16, 7, 27, 20, 13, 2, 
      41, 52, 31, 37, 47, 55, 30, 40, 
      51, 45, 33, 48, 44, 49, 39, 28, 
      34, 53, 46, 42, 50, 36, 29, 32
    };

  /* Mapping table from the 56-bits key K to the second round-key K2 */
  static uint8_t mapKtoK2[48]=
    {
      15, 18, 12, 25, 2, 6, 4, 1, 
      16, 7, 22, 11, 24, 20, 13, 5, 
      27, 9, 17, 8, 0, 21, 14, 3, 
      42, 53, 32, 38, 48, 28, 31, 41, 
      52, 46, 44, 49, 45, 50, 40, 29, 
      35, 54, 47, 43, 51, 37, 30, 33
    };

  /* Initialize the main key array */
  for(i = 0; i < 56; i++)
    K[i] = '\0';

  /* Mapping back the values from K1 to K (there will be 8 "holes" in K)*/
  for (i=0; i<48 ; i++){
    j=mapKtoK1[i];
    K[j]=K1[i];
  }

  /* Mapping back the values from K2 to K (will fill the "holes")*/
  for (i=0; i<48 ; i++){
    j=mapKtoK2[i]; /*j is uchar. if doesn't work convert it to int */
    K[j]=K2[i];
  }



}
	

int main() {
  int i;

  uchar K1[6] = 
    {
      0xF0,
      0xBE,
      0x66,
      0xB8,
      0x70,
      0x32
    };

  uchar K2[6] = 
    {
      0xE0,
      0xBE,
      0x76,
      0x9B,
      0x49,
      0xA5
    };

  uchar K[8];

  deduceKey(K1,K2,K);

  for(i=0; i<8; i++)
    printf("%02X",K[i]);

  return 0;
}
